﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;

namespace NotifyPilot.WCF.NotifyClients
{
    public class SignalRHubNotifyClient : NotifyClient, INotifyClient
    {
        private static IPersistentConnectionContext _context;

        public SignalRHubNotifyClient(String xmlEvent, String tfsRootUrl)
            : base(xmlEvent, tfsRootUrl)
        {
            if (_context == null)
            {
                // Use a Low Level Connection
                _context = GlobalHost.ConnectionManager.GetConnectionContext<SendEventConnection>();
            }
        }

        public void Post()
        {
            try
            {
                _context.Connection.Broadcast(this.ContentObject);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("TFS Notify Client - SignalR notifier",
                    String.Format("SignalR error thrown in Streaming broadcast: {0} |{1}",
                            ex.Message, ex.StackTrace), EventLogEntryType.Error);
            }
        }
    }

    public class SendEventConnection : PersistentConnection
    {
        // ReSharper disable once RedundantOverridenMember
        protected override Task OnConnected(IRequest request, string connectionId)
        {
            return base.OnConnected(request, connectionId);
        }
    }
}